//
//  LyricUtil.swift
//  歌词相关工具类
//
//  Created by smile on 2019/6/28.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

class LyricUtil {

    /// 计算当前播放时间是哪一行歌词
    ///
    /// - Parameters:
    ///   - lyric: 歌词对象
    ///   - time: 播放时间；单位秒
    /// - Returns: <#return value description#>
    static func getLineNumber(_ lyric:Lyric,_ time:Float) -> Int {
        //将播放时间转为毫秒
        let newTime = time * 1000
        
        //倒序遍历每一行歌词
        for (index,value) in lyric.datas.enumerated().reversed() {
            if newTime >=  Float(value.startTime) {
                //print("LyricUtil getLineNumber:\(newTime),\(index)")
                
                //就是这一行歌词
                return index
            }
        }
        
        return 0
    }
    
    /// 获取当前播放时间对应该行歌词第几个字
    ///
    /// - Parameters:
    ///   - data: <#data description#>
    ///   - time: <#time description#>
    /// - Returns: <#return value description#>
    static func getWordIndex(_ data:LyricLine,_ time:Float) -> Int {
        
        //转为毫秒
        let newTime = Int(time*1000)
        
        //这一行的开始时间
        var startTime = data.startTime
        
        //循环所有字的持续时间
        for (index,value) in data.wordDurations!.enumerated() {
            startTime = startTime + value
            if newTime < startTime {
                print("LyricUtil getWordIndex:\(data.data!),\(startTime),\(newTime),\(index)")
                return index
            }
        }
        
        return -1
    }
    
    /// 获取当前字播放的时间
    ///
    /// - Parameters:
    ///   - data: <#data description#>
    ///   - time: <#time description#>
    /// - Returns: <#return value description#>
    static func getWordPlayedTime(_ data:LyricLine,_ time:Float) -> Int {
        
        //转为毫秒
        let newTime = Int(time * 1000)
        
        //这一行歌词开始时间
        var startTime = data.startTime
        
        //循环遍历所有字持续时间
        for (index,value) in data.wordDurations!.enumerated() {
            startTime = startTime+value
            if newTime < startTime {
                let playedTime = value-(startTime-newTime)
                print("LyricUtil getWordPlayedTime:\(data.data),\(startTime),\(newTime),\(playedTime)")
                return playedTime
            }
        }
        
        return -1
    }
}
